package com.woniuxy.config;

import com.woniuxy.Mapper.AppointmentMapper;
import com.woniuxy.Mapper.OrderMapper;
import com.woniuxy.client.OrderServiceFeignClient;
import com.woniuxy.entity.ShopOrders;
import com.woniuxy.service.EmailService;
import com.woniuxy.utils.ResponseResult;
import com.woniuxy.vo.AppointmentsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class RedisKeyExpirationListener implements MessageListener {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    EmailService emailService;
    @Autowired
    AppointmentMapper appointmentMapper;
    private RedisMessageListenerContainer redisMessageListenerContainer;

    // 使用 @Autowired 字段注入（或 Setter 注入）
    @Autowired
    public void setRedisMessageListenerContainer(RedisMessageListenerContainer redisMessageListenerContainer) {
        this.redisMessageListenerContainer = redisMessageListenerContainer;
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 过期key的格式：__keyevent@0__:expired
        String expiredKey = new String(message.getBody());
        String channel = new String(pattern);
        System.out.println("收到Redis过期事件 - 频道: {}, Key: {}"+channel+expiredKey);
        // 只处理预约相关的key
        if(expiredKey.startsWith("appointment:unpaid")) {
            // 解析key获取订单号
            String[] parts = expiredKey.split(",");
            System.out.println("处理参数1"+parts+"---"+parts.length);
            if(parts.length ==5) {
                String userId=  parts[1];
                String date=  parts[2];
                String timeSolt=  parts[3];
                String orderNumber =  parts[4];
                System.out.println("处理参数：userId:"+userId+"date:"+date+"timeSolt:"+timeSolt+"orderNumber : "+orderNumber);
                cancelUnpaidOrder(userId,date,timeSolt,orderNumber);
            }
        }
    }

    private void cancelUnpaidOrder( String userId, String date, String timeSolt,String orderNumber) {
        log.info("开始处理未支付订单取消：{}", userId);
        System.out.println("开始处理未支付订单取消：userId:"+userId+"date:"+date+"timeSolt:"+timeSolt);

        // 根据 userId  date  timeSolt 查询订单状态
        AppointmentsVo orderResult= orderMapper.getOrderByUserId(1,orderNumber);
        System.out.println("orderResult.getStatus()"+orderResult);
        if(orderResult != null && orderResult.getStatus() == 1 && orderResult.getStatus() != 2){
            System.out.println("取消该未支付的订单"+orderResult.getOrderNumber());
            int i=  orderMapper.updateOrderStatus(orderResult.getOrderNumber(), 4);
            int j= appointmentMapper.updateAppStatusByOderNumber(orderResult.getOrderNumber(), "已取消");
            System.out.println(orderResult.getScheduleId()+"排班信息"+orderResult);
            int k=appointmentMapper.increseAppointmentCounts(orderResult.getScheduleId());
            System.out.println("执行情况, "+i+" - "+j+" - "+k);
            emailService.sendToQQEmail("1285161740@qq.com", "智慧养老院", "尊敬的用户,您于"+date+" " +timeSolt+"预约的的门诊,超过半小时未支付已经取消");
        }
    }
}